package com.pmpd.activity.controller.api;

import com.dmap.base.constants.Constant;
import com.dmap.base.vo.BaseVo;
import com.pmpd.activity.constants.ActivityConstant;
import com.pmpd.activity.controller.api.param.ActivityUserParam;
import com.pmpd.activity.bo.api.ActivityWinningUserBo;
import com.pmpd.activity.po.ActivityProgress;
import com.pmpd.activity.po.ActivityUser;
import com.pmpd.activity.rpc.ActivityUCenterRpc;
import com.pmpd.activity.service.api.ApiActivityProgressService;
import com.pmpd.activity.service.api.ApiActivityUserService;
import com.pmpd.activity.vo.api.ApiActivityUserVo;
import com.pmpd.activity.vo.api.ApiActivityWinningVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * @Author liuying
 * @Description 活动用户关联控制层
 * @Date 14:45 2018/6/7
 */
@Api(value = "App/用户活动API", description = "App/用户活动API")
@RestController
@RequestMapping(value = "/api/pmpd-activity-server/v1/activity/activityUser")
public class ApiActivityUserController {

    @Resource
    private ApiActivityUserService apiActivityUserService;

    @Resource
    private ActivityUCenterRpc activityUserRpc;

    @Resource
    private ApiActivityProgressService apiActivityProgressService;

    @ResponseBody
    @ApiOperation(value = "获取用户活动参与情况", notes = "1. 返回为null，则为未参加活动，其余信息在返回的活动用户对象中。")
    @RequestMapping(value = "/select/selectActivityUser", method = RequestMethod.POST)
    public BaseVo selectActivityUser(@RequestBody ActivityUserParam param) {
        BaseVo baseVo = new BaseVo();
        if (param == null || StringUtils.isEmpty(param.getActivityId()) || Long.parseLong(param.getActivityId()) == 0 
                || StringUtils.isEmpty(param.getUserId()) || Long.parseLong(param.getUserId()) == 0) {
            baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
            return baseVo;
        }

        List<ActivityUser> users = apiActivityUserService.selectByActivityIdAndUserId(Long.parseLong(param.getActivityId()), Long.parseLong(param.getUserId()));
        if (CollectionUtils.isNotEmpty(users)){
            baseVo.setData(new ApiActivityUserVo(users.get(0)));
        } else {
            //判断是否在报名时间内
            long seconds = System.currentTimeMillis() / 1000;
            if (seconds < ActivityConstant.TIME_ACTIVITY_BEGIN || seconds > ActivityConstant.TIME_USER_APPLY_END){
                baseVo.setCode(ActivityConstant.RESPONSE_NOT_IN_APPLY_TIME_ERROR_CODE);
                baseVo.setMsg(ActivityConstant.RESPONSE_NOT_IN_APPLY_TIME_ERROR_MSG);
            }

        }
        return baseVo;
    }

    @ResponseBody
    @ApiOperation(value = "获取加入该类型活动人数", notes = "1. 参数中的userId不填")
    @RequestMapping(value = "/select/countByActivityAndType", method = RequestMethod.POST)
    public BaseVo countByActivityAndType(@RequestBody ActivityUserParam param) {
        BaseVo baseVo = new BaseVo();
        if (param == null || StringUtils.isEmpty(param.getActivityId()) || Long.parseLong(param.getActivityId()) == 0 
                || param.getType() == 0) {
            baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
            return baseVo;
        }

        int userCount = apiActivityUserService.countByActivityAndType(Long.parseLong(param.getActivityId()), param.getType());

        baseVo.setData(userCount);
        return baseVo;
    }

    @Transactional
    @ResponseBody
    @ApiOperation(value = "用户加入某类型活动", notes = "用户加入某类型活动")
    @RequestMapping(value = "/add/addActivity", method = RequestMethod.POST)
    public BaseVo addActivity(@RequestBody ActivityUserParam param) {
        BaseVo baseVo = new BaseVo();
        if (param == null || StringUtils.isEmpty(param.getActivityId()) || Long.parseLong(param.getActivityId()) == 0  
                || param.getType() == 0 || StringUtils.isEmpty(param.getUserId()) || Long.parseLong(param.getUserId()) == 0) {
            baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
            return baseVo;
        }

        long userId = Long.parseLong(param.getUserId());
        long activityId = Long.parseLong(param.getActivityId());

        //判断是否为此活动
        if (activityId != ActivityConstant.SEVEN_DAYS_TRAINING_ID){
            baseVo.setCode(ActivityConstant.RESPONSE_NO_DATA_ERROR_CODE);
            baseVo.setMsg(ActivityConstant.RESPONSE_NO_DATA_ERROR_MSG);
            return baseVo;
        }

        //判断是否在报名时间内
        long seconds = System.currentTimeMillis() / 1000;
        if (seconds < ActivityConstant.TIME_ACTIVITY_BEGIN || seconds > ActivityConstant.TIME_USER_APPLY_END){
            baseVo.setCode(ActivityConstant.RESPONSE_NOT_IN_APPLY_TIME_ERROR_CODE);
            baseVo.setMsg(ActivityConstant.RESPONSE_NOT_IN_APPLY_TIME_ERROR_MSG);
            return baseVo;
        }

        //判断是否已加入活动
        ActivityUser hadUser = apiActivityUserService.ActivityUserByUserId(activityId, userId);
        if (hadUser != null){
            baseVo.setCode(ActivityConstant.RESPONSE_JOIN_ACTIVITY_ERROR_CODE);
            baseVo.setMsg(ActivityConstant.RESPONSE_JOIN_ACTIVITY_ERROR_MSG + hadUser.getType());
            return baseVo;
        }

        //所有用户都需加入用户表
        ActivityUser activityUser = apiActivityUserService.addActivity(activityId, userId, param.getType(), param.getProjectId(), seconds);
        if (activityUser == null){
            baseVo.setCode(Constant.RESPONSE_INSERT_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_INSERT_ERROR_MSG);
            return baseVo;
        }

        //当前时间的小时数
        int hours = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
        if (hours < ActivityConstant.TASK_JUDGE_HOUR_OF_DAY){
            //当前时间小于 是否第二天开始任务的小时数，则创建当天活动进程
            ActivityProgress activityProgress = apiActivityProgressService.addProgress(activityId, userId, param.getType(), seconds);
            if (activityProgress == null) {
                baseVo.setCode(Constant.RESPONSE_INSERT_ERROR_CODE);
                baseVo.setMsg(Constant.RESPONSE_INSERT_ERROR_MSG);
                return baseVo;
            }
        } else if (hours >= ActivityConstant.TIMER_TASK_INSERT_HOUR_OF_DAY){
            //如果在 定时批量新增第二天的进程的时间之后，在 第二日零点之前，加入活动，则需新增第二天的进程
            ActivityProgress nextDayProgress = apiActivityProgressService.addNextDayProgress(activityId, userId, seconds);
            if (nextDayProgress == null) {
                baseVo.setCode(Constant.RESPONSE_INSERT_ERROR_CODE);
                baseVo.setMsg(Constant.RESPONSE_INSERT_ERROR_MSG);
                return baseVo;
            }
        }

        baseVo.setData(seconds);
        return baseVo;
    }

    @ResponseBody
    @ApiOperation(value = "获取用户完成任务数", notes = "1. 参数中type不填;")
    @RequestMapping(value = "/select/completeCountByUserId", method = RequestMethod.POST)
    public BaseVo completeCountByUserId(@RequestBody ActivityUserParam param) {
        BaseVo baseVo = new BaseVo();
        if (param == null || StringUtils.isEmpty(param.getActivityId()) || Long.parseLong(param.getActivityId()) == 0
                || StringUtils.isEmpty(param.getUserId()) || Long.parseLong(param.getUserId()) == 0) {
            baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
            return baseVo;
        }

        int finishDays = apiActivityProgressService.getFinishDays(Long.parseLong(param.getUserId()), Long.parseLong(param.getActivityId()));

        baseVo.setData(finishDays);
        return baseVo;
    }

    @ResponseBody
    @ApiOperation(value = "参与抽奖", notes = "1. 参数中type不填;")
    @RequestMapping(value = "/update/joinWinning", method = RequestMethod.POST)
    public BaseVo joinWinning(@RequestBody ActivityUserParam param) {
        BaseVo baseVo = new BaseVo();
        if (param == null || StringUtils.isEmpty(param.getActivityId()) || Long.parseLong(param.getActivityId()) == 0
                || StringUtils.isEmpty(param.getUserId()) || Long.parseLong(param.getUserId()) == 0 
                || param.getAwardDay() == 0) {
            baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
            return baseVo;
        }

        ActivityUser result = apiActivityUserService.updateWinningState(Long.parseLong(param.getActivityId())
                , Long.parseLong(param.getUserId()), param.getAwardDay());

        if (result == null){
            baseVo.setCode(Constant.RESPONSE_UPDATE_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_UPDATE_ERROR_MSG);
        }
        return baseVo;
    }

    @ResponseBody
    @ApiOperation(value = "判断是否中奖或是否参与抽奖", notes = "判断是否中奖或是否参与抽奖")
    @RequestMapping(value = "/select/isWinning", method = RequestMethod.POST)
    public BaseVo isWinning(@RequestBody ActivityUserParam param) {
        BaseVo baseVo = new BaseVo();
        if (param == null || StringUtils.isEmpty(param.getActivityId()) || Long.parseLong(param.getActivityId()) == 0
                || StringUtils.isEmpty(param.getUserId()) || Long.parseLong(param.getUserId()) == 0 
                || param.getWinningState() == 0) {
            baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
            return baseVo;
        }

        int winningState = apiActivityUserService.isWinning(Long.parseLong(param.getActivityId())
                , Long.parseLong(param.getUserId()));

        if (param.getWinningState() == ActivityConstant.STATE_JOIN_WINNING){
            //判断是否参与抽奖
            baseVo.setData(winningState == ActivityConstant.STATE_WINNING);
        } else if (param.getWinningState() == ActivityConstant.STATE_WINNING){
            //判断是否中奖
            baseVo.setData(winningState == ActivityConstant.STATE_JOIN_WINNING);
        } else {
            baseVo.setData(false);
        }
        return baseVo;
    }

    @ResponseBody
    @ApiOperation(value = "查询中奖用户信息列表", notes = "查询中奖用户信息列表")
    @RequestMapping(value = "/select/getAwardUsers", method = RequestMethod.POST)
    public BaseVo getAwardUsers(@RequestBody ActivityUserParam param) {
        BaseVo baseVo = new BaseVo();
        if (param == null || StringUtils.isEmpty(param.getActivityId()) || Long.parseLong(param.getActivityId()) == 0 
                || param.getAwardDay() == 0) {
            baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
            return baseVo;
        }

        List<Long> list = apiActivityUserService.getAwardUser(Long.parseLong(param.getActivityId()), param.getAwardDay());
        if (CollectionUtils.isEmpty(list)){
            baseVo.setData(new ArrayList());
            return baseVo;
        }

        //从UCenter模块获取user数据
        List<ActivityWinningUserBo> users = activityUserRpc.selectUserList(list);

        List<ApiActivityWinningVo> voList = new ArrayList<>();
        users.forEach(ActivityWinningUserBo ->
                voList.add(new ApiActivityWinningVo(ActivityWinningUserBo))
        );
        baseVo.setData(voList);
        return baseVo;
    }

}
